#!/usr/bin/env python
# -*- coding: utf-8 -*-

from datetime import datetime
from enum import Enum
from persistent import Persistent
from persistent.list import PersistentList
from persistent.mapping import PersistentMapping
from web_server.device_proxy import DeviceProxy
from web_server.models.db_client import DBClient

class PermType(Enum):
    """权限类型枚举"""
    READ = "read"           # 读取权限
    WRITE = "write"         # 写入权限
    EXECUTE = "execute"     # 执行权限
    DELETE = "delete"       # 删除权限
    CREATE = "create"       # 创建权限
    ADMIN = "admin"         # 管理权限
    SHARE = "share"         # 分享权限

class BasePerm(Persistent):
    """权限关联基类"""
    
    def __init__(self, project_path, permissions: [PermType], granted_by=None, expires_at=None):
        super().__init__()
        if permissions is None or len(permissions) == 0:
            # 设置默认的最小权限（只读）
            permissions = [PermType.READ]
        self.project_path = project_path
        self.permissions = PersistentList(permissions)
        self.granted_by = granted_by
        self.granted_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.expires_at = expires_at
    
    def has_perms(self, permissions):
        """检查是否具有指定权限"""
        if permissions is None or len(permissions) == 0:
            return True
        for perm in permissions:
            if perm not in self.permissions:
                return False
        return True

class UserPerm(BasePerm):
    def __init__(self, username, project_path, **kwargs):
        super().__init__(project_path, **kwargs)
        self.username = username

class RolePerm(BasePerm):
    def __init__(self, role_name, project_path, **kwargs):
        super().__init__(project_path, **kwargs)
        self.role_name = role_name

class GroupPerm(BasePerm):
    def __init__(self, group_name, project_path, **kwargs):
        super().__init__(project_path, **kwargs)
        self.group_name = group_name